<template>
  <el-container style="height: calc(100vh - 60px);">
    <!-- 顶部导航 -->
    <el-header height="60px" class="header">
      <div class="nav-container">
        <el-menu mode="horizontal" :default-active="activeIndex" class="menu" router>
          <el-menu-item index="/" @click="goHome">
            <span style="font-weight: bold; font-size: 18px;">品牌商城</span>
          </el-menu-item>

          <!-- 首页菜单项 -->
          <el-menu-item index="/" @click="goHome">
            <el-icon><House /></el-icon>
            <span>首页</span>
          </el-menu-item>

          <el-sub-menu index="products">
            <template #title>
              <el-icon><Goods /></el-icon>
              <span>产品</span>
            </template>
            <el-menu-item @click="goPhone">手机</el-menu-item>
            <el-menu-item @click="goLaptop">笔记本</el-menu-item>
            <el-menu-item @click="goTablet">平板</el-menu-item>
          </el-sub-menu>

          <el-menu-item index="/about">关于我们</el-menu-item>
        </el-menu>

        <!-- 移到导航栏最右侧 -->
        <div class="header-right">
          <el-button type="primary" :icon="ShoppingCart" circle class="cart-btn" />

          <!-- 登录状态显示 -->
          <div v-if="isLoggedIn" class="user-info">
            <el-dropdown>
              <span class="user-name">
                <el-icon><User /></el-icon>
                {{ currentUser?.name || currentUser?.username || '用户' }}
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goHome">返回首页</el-dropdown-item>
                  <el-dropdown-item>个人中心</el-dropdown-item>
                  <el-dropdown-item divided @click="handleLogout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>

          <!-- 未登录状态显示 -->
          <el-button
              v-else
              type="primary"
              :icon="User"
              class="login-btn"
              @click="openLoginDialog"
          >
            登录
          </el-button>
        </div>
      </div>
    </el-header>

    <!-- 登录弹窗 -->
    <el-dialog
        v-model="loginDialogVisible"
        :title="isRegister ? '用户注册' : '用户登录'"
        width="400px"
        :before-close="() => loginDialogVisible = false"
    >
      <el-form :model="loginForm" label-width="80px">
        <el-form-item label="用户名">
          <el-input
              v-model="loginForm.username"
              placeholder="请输入用户名"
              @keyup.enter="submitAuth"
          />
        </el-form-item>
        <el-form-item label="密码">
          <el-input
              v-model="loginForm.password"
              type="password"
              placeholder="请输入密码"
              @keyup.enter="submitAuth"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div style="text-align: center; width: 100%;">
          <el-button
              type="primary"
              :loading="loading"
              @click="submitAuth"
              style="width: 100%; margin-bottom: 10px;"
          >
            {{ isRegister ? '注册' : '登录' }}
          </el-button>

          <el-link
              type="primary"
              @click="isRegister = !isRegister"
          >
            {{ isRegister ? '已有账号？去登录' : '没有账号？立即注册' }}
          </el-link>
        </div>
      </template>
    </el-dialog>

    <!-- 下方主体：左侧固定导航 + 右侧内容 -->
    <el-container style="height: calc(100vh - 60px);">
      <!-- 左侧导航 -->
      <LeftNav @select="onCatSelect" />

      <!-- 右侧内容区域 -->
      <el-main class="right-main">
        <!-- 多品类墙 -->
        <div class="block home-wall">
          <h2 class="section-title">{{ currentTitle }}</h2>
          <el-row :gutter="16" justify="start">
            <el-col
                v-for="p in wallProducts"
                :key="p.id"
                :xs="24"
                :sm="12"
                :md="8"
                :lg="8"
                :xl="6"
                class="home-card"
            >
              <el-image
                  :src="p.img"
                  :preview-src-list="[p.img]"
                  fit="cover"
                  class="home-img"
                  @click="goDetail(p.id)"
              />
              <h4 class="home-name">{{ p.name }}</h4>
              <p class="home-price">¥{{ p.price }}</p>
              <el-button
                  type="danger"
                  size="small"
                  class="home-btn"
                  @click="goDetail(p.id)"
              >
                查看详情
              </el-button>
            </el-col>
          </el-row>
        </div>
      </el-main>
    </el-container>
  </el-container>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ShoppingCart, User, House, Goods } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import LeftNav from '../components/LeftNav.vue'
import { getCategories, login, register } from '../api/service'

const route = useRoute()
const router = useRouter()

const activeIndex = ref(route.path)
const currentTitle = ref('热门商品')
const wallProducts = ref<any[]>([])
const categories = ref<any[]>([])

// 监听路由变化，确保首页高亮
watch(() => route.path, (newPath) => {
  activeIndex.value = newPath
})
/* 跳转到首页 */
const goHome = () => {
  router.push('/')
  // 重置首页状态
  currentTitle.value = '热门商品'
  wallProducts.value = homeWall
}
// 登录状态
const isLoggedIn = ref(!!localStorage.getItem('token'))
const currentUser = ref(JSON.parse(localStorage.getItem('user') || 'null'))

// 登录弹窗相关
const loginDialogVisible = ref(false)
const loginForm = reactive({
  username: '',
  password: ''
})
const isRegister = ref(false)
const loading = ref(false)

/* 打开登录弹窗 */
const openLoginDialog = () => {
  loginDialogVisible.value = true
  loginForm.username = ''
  loginForm.password = ''
  isRegister.value = false
}

/* 提交登录/注册 */
const submitAuth = async () => {
  if (!loginForm.username || !loginForm.password) {
    ElMessage.warning('请输入用户名和密码')
    return
  }

  loading.value = true
  try {
    let result
    if (isRegister.value) {
      // 注册
      const res = await register(loginForm.username, loginForm.password)
      result = res.success ? { success: true, message: res.message } : { success: false, message: res.message }
    } else {
      // 登录
      const res = await login(loginForm.username, loginForm.password)
      if (res.success) {
        currentUser.value = res.data.user
        isLoggedIn.value = true
        localStorage.setItem('token', res.data.token)
        localStorage.setItem('user', JSON.stringify(res.data.user))
        result = { success: true }
      } else {
        result = { success: false, message: res.message }
      }
    }

    if (result.success) {
      ElMessage.success(isRegister.value ? '注册成功！' : '登录成功！')
      loginDialogVisible.value = false
      if (!isRegister.value) {
        setTimeout(() => location.reload(), 500)
      }
    } else {
      ElMessage.error(result.message || '操作失败')
    }
  } catch (error) {
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

/* 退出登录 */
const handleLogout = () => {
  localStorage.removeItem('token')
  localStorage.removeItem('user')
  isLoggedIn.value = false
  currentUser.value = null
  ElMessage.success('已退出登录')
}

/* 首页墙数据 */
const homeWall = [
  { id: 1, name: 'HUAWEI Pura 80 Pro', price: 5999, img: 'https://consumer-img.huawei.com/content/dam/huawei-cbg-site/common/mkt/pdp/phones/pura-70-ultra/pc/product-kv.png', cat: 1 },
  { id: 2, name: 'Xiaomi 14 Ultra', price: 6499, img: 'https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/8f70a3b8f75ae0b4b69e0e0e0e0e0e0e.png', cat: 1 },
  { id: 3, name: 'iPhone 15 Pro', price: 7999, img: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-15-pro-finish-select-202309-6-7inch-naturaltitanium?wid=5120&hei=2880&fmt=p-jpg&qlt=80&.v=1692846359318', cat: 1 },
  { id: 4, name: 'OPPO Find X7 Ultra', price: 5999, img: 'https://images.unsplash.com/photo-1511707171634-5f897ff02aa9?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=500&q=80', cat: 1 },
  { id: 5, name: 'vivo X100 Pro', price: 4999, img: 'https://images.unsplash.com/photo-1511707171634-5f897ff02aa9?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=500&q=80', cat: 1 },
  { id: 6, name: 'MacBook Pro 14', price: 15999, img: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/mbp14-silver-select-202110?wid=904&hei=840&fmt=jpeg&qlt=90&.v=1632799173000', cat: 2 },
  { id: 7, name: 'Xiaomi Book Pro 16', price: 6499, img: 'https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/8f70a3b8f75ae0b4b69e0e0e0e0e0e0e.png', cat: 2 },
  { id: 8, name: 'HUAWEI MateBook X Pro', price: 8999, img: 'https://consumer-img.huawei.com/content/dam/huawei-cbg-site/common/mkt/list/pc/matebook-x-pro-2024.png', cat: 2 },
  { id: 9, name: 'Dell XPS 13', price: 9999, img: 'https://images.unsplash.com/photo-1496181133206-80ce9b88a853?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=500&q=80', cat: 2 },
  { id: 10, name: 'iPad Pro 12.9', price: 8499, img: 'https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/ipad-pro-12-select-wifi-spacegray-202104?wid=940&hei=1112&fmt=p-jpg&qlt=95&.v=1617126635000', cat: 3 },
  { id: 11, name: 'HUAWEI MatePad Pro', price: 3999, img: 'https://consumer-img.huawei.com/content/dam/huawei-cbg-site/common/mkt/list/tablet/matepad-pro-13-2.png', cat: 3 },
  { id: 12, name: 'Xiaomi Pad 6', price: 1999, img: 'https://cdn.cnbj1.fds.api.mi-img.com/mi-mall/8f70a3b8f75ae0b4b69e0e0e0e0e0e0e.png', cat: 3 }
]

/* 路由跳转 */
const goPhone   = () => { router.push('/product?id=1') }
const goLaptop  = () => { router.push('/product?id=6') }
const goTablet  = () => { router.push('/product?id=10') }
const goDetail  = (id: number) => { router.push(`/product?id=${id}`) }

/* 左侧点击分类：过滤当前墙 */
const onCatSelect = (selection: any) => {
  console.log('选中的分类:', selection)

  if (selection.type === 'category') {
    // 主分类点击
    const filtered = homeWall.filter(p => p.cat === selection.categoryId)
    wallProducts.value = filtered.length > 0 ? filtered : homeWall.slice(0, 4)
    currentTitle.value = `${selection.name} 推荐`
  }
  else if (selection.type === 'subcategory') {
    // 子分类点击 - 根据 productIds 过滤商品
    const filtered = homeWall.filter(p => selection.productIds.includes(p.id))
    wallProducts.value = filtered.length > 0 ? filtered : homeWall.slice(0, 4)
    currentTitle.value = `${selection.name} - 精选`

    // 如果只有一个商品，直接跳转到详情页
    if (filtered.length === 1) {
      goDetail(filtered[0].id)
    }
  }
}

onMounted(async () => {
  try {
    categories.value = await getCategories()
    wallProducts.value = homeWall
    currentTitle.value = '热门商品'
  } catch (error) {
    console.error('加载分类失败:', error)
    categories.value = [
      { id: 1, name: '手机' },
      { id: 2, name: '笔记本' },
      { id: 3, name: '平板' }
    ]
    wallProducts.value = homeWall
  }
})
</script>

<style scoped>
html, body, #app {
  height: 100%;
  margin: 0;
}

.header {
  padding: 0;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,.1);
  position: sticky;
  top: 0;
  background: white;
  z-index: 1000;
}

.nav-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100%;
  padding: 0 20px;
}

.menu {
  flex: 1;
  border-bottom: none;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-left: auto;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-name {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
  color: #409EFF;
  font-weight: 500;
}

.user-name:hover {
  background-color: #f5f5f5;
}

.right-main {
  padding: 30px 20px;
  overflow-y: auto;
  background: #fafafa;
  height: calc(100vh - 60px);
  margin-left: 240px;
  width: calc(100% - 240px);
}

.home-wall {
  margin-top: 20px;
}

.home-card {
  text-align: center;
  padding: 16px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0,0,0,.08);
  transition: transform .3s, box-shadow .3s;
  margin-bottom: 16px;
}

.home-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 16px rgba(0,0,0,.12);
}

.home-img {
  width: 100%;
  height: 180px !important;
  border-radius: 6px;
  object-fit: cover;
  cursor: pointer;
}

.home-name {
  margin: 12px 0 6px;
  font-size: 16px;
  color: #333;
  font-weight: 600;
  line-height: 1.4;
  height: 44px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.home-price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
  margin-bottom: 10px;
}

.home-btn {
  width: 100%;
  font-size: 12px;
  padding: 8px 12px;
}

.section-title {
  text-align: center;
  font-size: 28px;
  color: #333;
  margin-bottom: 30px;
  font-weight: 600;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .right-main {
    margin-left: 0;
    width: 100%;
    padding: 20px 10px;
  }

  .home-card {
    padding: 12px;
  }

  .home-img {
    height: 150px !important;
  }

  .home-name {
    font-size: 14px;
    height: 40px;
  }

  .home-price {
    font-size: 16px;
  }
}

/* 确保左侧导航栏不会遮挡内容 */
:deep(.left-aside) {
  z-index: 998;
}

:deep(.right-main) {
  position: relative;
  z-index: 1;
}

:deep(.el-menu--horizontal) {
  border-bottom: none;
}

:deep(.el-menu--horizontal > .el-menu-item) {
  height: 60px;
  line-height: 60px;
}

:deep(.el-menu--horizontal > .el-sub-menu .el-sub-menu__title) {
  height: 60px;
  line-height: 60px;
}
/* 品牌Logo样式 */
:deep(.el-menu-item [style*="font-weight: bold"]) {
  color: #409EFF;
  font-size: 20px !important;
}

/* 首页菜单项样式 */
:deep(.el-menu-item .el-icon) {
  margin-right: 5px;
}

/* 确保首页菜单项高亮 */
:deep(.el-menu-item.is-active) {
  color: #409EFF !important;
  border-bottom: 2px solid #409EFF;
}
</style>